package com.gjun.struts.resource;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.gjun.struts.bean.GjunMainTypeJson2Bean;
import com.gjun.struts.bean.GjunMainTypeJsonBean;
import com.gjun.struts.bean.GjunMaintype;
import com.gjun.struts.bean.GjunNews;

public class GjunMainTypeResourceDAO extends HibernateDaoSupport implements
		GjunMainTypeResourceIf {

	
	public boolean updateMainTypeNewsStateToActive(final int id) throws Exception {
		// TODO Auto-generated method stub
		int result = (Integer)this.getHibernateTemplate().execute(new HibernateCallback(){
			
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				Query q = session.createQuery("update GjunNews n set n.state= 1 where n.maintype.id=? and n.state=0 and n.endnews>?");
				q.setParameter(0,id);
				q.setParameter(1,new Date());
				
				return q.executeUpdate();
			}
		});
		return result>0?true:false;
	}
	public boolean updateMainType(final int id, String info, String typename, String filePath) throws Exception {
		// TODO Auto-generated method stub
		//System.out.println("filePath:  "+filePath);
		GjunMaintype mt = (GjunMaintype)this.getHibernateTemplate().execute(new HibernateCallback(){
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				// TODO Auto-generated method stub
				Query q = session.createQuery("from GjunMaintype mt where mt.id=?");
				q.setParameter(0,id);
				return q.uniqueResult();
			}
		});
		mt.setInfo(info);
		mt.setTypename(typename);
		if(filePath!=null){
			mt.setImage(filePath);
		}
		return true;
	}
	public boolean loadMainTypeByNameAndId(final String name,final int id) {
		return (Boolean) this.getHibernateTemplate().execute(
				new HibernateCallback() {

					public Object doInHibernate(Session session)
							throws HibernateException, SQLException {
						Query q = session
								.createQuery("select count(*) from GjunMaintype mt where mt.typename=? and mt.id!=?");
						q.setParameter(0, name);
						q.setParameter(1, id);
						int count = ((Long) q.uniqueResult()).intValue();
						//System.out.println("count:  " + count);

						return count > 0 ? true : false;
					}
				});
	}
	
	public GjunMaintype loadMainTypeById(final int id) {
		// TODO Auto-generated method stub
		GjunMaintype mt = (GjunMaintype)this.getHibernateTemplate().execute(new HibernateCallback(){
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				// TODO Auto-generated method stub
				Query q = session.createQuery("from GjunMaintype mt where mt.id = ?");
				q.setParameter(0,id);
				return q.uniqueResult();
			}
		});
		return mt;
	}
	public boolean delMainTypeById(int id) throws Exception {
		try {
			GjunMaintype mt = (GjunMaintype) this.getHibernateTemplate().get(
					GjunMaintype.class, id);
			this.getHibernateTemplate().evict(mt.getNews());  
			this.getHibernateTemplate().delete(mt);
			return true;
		} catch (Exception ex) {
			ex.printStackTrace();
			throw ex;

		}

	}

	public List<GjunMainTypeJson2Bean> loadAllMainTypes() {

		final List<GjunMainTypeJson2Bean> beans = new ArrayList<GjunMainTypeJson2Bean>();

		this.getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query q = session.createQuery("from GjunMaintype mt");
				List<GjunMaintype> list = q.list();
				for (GjunMaintype mt : list) {
					// 1. 一个新闻主类型在页面中呈现的时候数据会包装成为 GjunMainTypeJson2Bean
					GjunMainTypeJson2Bean bean = new GjunMainTypeJson2Bean();

					// 2. 填充最基本的新闻主类型信息
					bean.setId(mt.getId());
					bean.setTypename(mt.getTypename());
					bean.setImage(mt.getImage());
					bean.setInfo(mt.getInfo());
					bean.setRegdate(mt.getRegdate());

					// 
					Set<GjunNews> news = mt.getNews(); // 要提取当前新闻分类的新闻数据
					int no_open_news_count = 0;
					int online_news_count = 0;
					int end_news_count = 0;
					int cancel_news_count = 0;
					int no_active_news_count = 0;
					int idle_count = 0;

					// 经过这些判断可以确定当前新闻分类存在新闻
					if (news != null && news.size() > 0) {

						for (GjunNews n : news) {
							// System.out.println(mt.getTypename()+"\t"+n.getTitle());
							// 激活但未上架新闻要求是上架时间大于当前时间,并且状态为1
							if (n.getOpennews().getTime() > new Date()
									.getTime()
									&& n.getState() == 1) {
								no_open_news_count++;
							}
							if (n.getOpennews().getTime() < new Date()
									.getTime()
									&& new Date().getTime() < n.getEndnews()
											.getTime() && n.getState() == 1) {
								online_news_count++;
							}
							if (new Date().getTime() > n.getEndnews().getTime()
									&& n.getState() == 1) {
								end_news_count++;
							}
							if (n.getState() == 2) {
								cancel_news_count++;
							}
							if (n.getState() == 0
									&& n.getEndnews().getTime() > new Date()
											.getTime()) {
								no_active_news_count++;
							}
							if (n.getState() == 0
									&& n.getEndnews().getTime() < new Date()
											.getTime()) {
								idle_count++;
							}

						}

					}

					// 设定关于当前新闻分类不同新闻状态的相关信息
					bean.setCancel_open(cancel_news_count);
					bean.setEnd_open(end_news_count);
					bean.setNo_open(no_open_news_count);
					bean.setOnline(online_news_count);
					bean.setNo_active(no_active_news_count);
					bean.setIdel(idle_count);
					beans.add(bean);
				}
				return null;
			}

		});

		return beans;

	}

	public boolean loadMainTypeByName(final String name) {
		// TODO Auto-generated method stub
		return (Boolean) this.getHibernateTemplate().execute(
				new HibernateCallback() {

					public Object doInHibernate(Session session)
							throws HibernateException, SQLException {
						Query q = session
								.createQuery("select count(*) from GjunMaintype mt where mt.typename=?");
						q.setParameter(0, name);
						int count = ((Long) q.uniqueResult()).intValue();
						//System.out.println("count:  " + count);

						return count > 0 ? true : false;
					}
				});
	}

	public void saveMainType(GjunMaintype mt) throws Exception {
		// TODO Auto-generated method stub
		this.getHibernateTemplate().save(mt);
	}

	public List<GjunMainTypeJsonBean> loadAllMainType() {
		// TODO Auto-generated method stub
		return (List<GjunMainTypeJsonBean>) this.getHibernateTemplate()
				.execute(new HibernateCallback() {

					public Object doInHibernate(Session session)
							throws HibernateException, SQLException {
						// TODO Auto-generated method stub
						Query q = session
								.createQuery("select new com.gjun.struts.bean.GjunMainTypeJsonBean(mt.typename,mt.id) from GjunMaintype mt ");
						return q.list();
					}
				});
	}

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"applicationContext.xml");
		GjunMainTypeResourceIf dao = (GjunMainTypeResourceIf) context
				.getBean("mainTypeDAO");
		
		/*
		List<GjunMainTypeJson2Bean> beans = dao.loadAllMainTypes();
		for (GjunMainTypeJson2Bean bean : beans) {
			System.out.println(bean.getId() + "\t" + bean.getTypename() + "\t"
					+ bean.getNo_open() + "\t" + bean.getOnline() + "\t"
					+ bean.getEnd_open() + "\t" + bean.getNo_active() + "\t"
					+ bean.getCancel_open() + "\t" + bean.getIdel());
		}
		*/
		try {
			dao.updateMainTypeNewsStateToActive(3);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
